<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/4/19
* Time: 8:41
*/
namespace app\admin\controller;

use app\admin\controller\Department;
use app\admin\model\DepartmentModel;
use app\admin\model\MemberModel;
use app\admin\model\RoleModel;
use think\Db;
use app\admin\model\OrderModel;
use app\admin\model\UserModel;
use app\admin\controller\Finance;
use app\admin\controller\Education;

class Member extends Base{
	//调用当前用户下的部门 13 -21
	public function _initialize(){
		parent::_initialize();
		$uid = session('id');
		if (empty(session('can_see')[0])) {
			$department_id =Db::name('department')->where(['pid'=>0])->value('id');
		}else{
			$role_id = Db::name('user')->where(['id'=>$uid])->value('role_id');
			$department_id =Db::name('role')->where(['id'=>$role_id])->value('department_id');
		}
		$roleModel = new RoleModel();
		$departUserID = $roleModel->getUsersByDepartIdCansee($department_id);
		$where['id'] = array('in',$departUserID);
		//查询当前部门下的所有职员
		$departUserArr = Db::name('user')->field(['id','real_name'])->where($where)->select();
		$myArr = Db::name('department')->where('id',$department_id)->find();
		$dep_Arr = $this->DeparArr($department_id);


		$myArr['children'] = $dep_Arr;
		$departArr[0] = $myArr;
		$option = $this->arr2Tree($departArr);
		$this->assign([
			'dep_Arr' 		=> $option,
			'departUserArr' => $departUserArr,
			'id' 			=> $uid
		]);
	}
	public function arr2Tree($arr,$option='',$strk = ''){
		$str = '| - ';
		foreach($arr as $v){
			$option .= '<option value="'.$v['id'].'">'.$str.$strk.$v['name'].'</option>';
			if(!empty($v['children'])){
				$strk .= '- - ';
				$option = $this->arr2Tree($v['children'],$option,$strk);
				$strk = mb_substr($strk,4,mb_strlen($strk));
			}
		}
		return $option;
	}

	public function DeparArr($id){
		$arr= [];
		$departArr = Db::name('department')->where('pid',$id)->select();
		foreach ($departArr as $key => $value){
			$value['children'] = $this->DeparArr($value['id']);
			$arr[] = $value;
		}
		return $arr;
	}

	// public function getMydeparts ($id){
	// 	$departModel = new DepartmentModel();
	// 	$arr = $departModel->getSonsByPid($id);
	// 	$brr = [];
	// 	foreach($arr as $v){
	// 		array_push($brr,DB::name('department')->where('id',$v['id'])->find());
	// 	}
	// 	print_r($brr);die;
	// 	return getTree($brr);
	// }

	public function getDepartArr(){
		$uid = session('id');
		if (empty(session('can_see')[0])) {
			$department_id =Db::name('department')->where(['pid'=>0])->value('id');
		}else{
			$role_id = Db::name('user')->where(['id'=>$uid])->value('role_id');
			$department_id =Db::name('role')->where(['id'=>$role_id])->value('department_id');
		}
		$myArr = Db::name('department')->where('id',$department_id)->find();
		$dep_Arr = $this->DeparArr($department_id);
		$myArr['children'] = $dep_Arr;
		$departArr[0] = $myArr;
		return json(msg(1, $departArr, 'ok'));
	}
	//Ajax 获取选择部门的职员信息
	public function departUser(){
		$depart_id = input('post.depart_id');
		// $roleModel = new RoleModel();
		$finance = new Finance();
		$departUserID = $finance->getAllRolesAndAllUsersByParentDepart($depart_id);
		// print_r($departUserID);die;
		$where['id'] = array('in',$departUserID['userArr']);
		//查询当前部门下的所有职员
		$departUserArr = Db::name('user')->where($where)->field(['id','real_name'])->select();
		return json(['code'=>1,'data'=>$departUserArr]);
	}
	/**
	* 会员管理
	* 18-4-19
	*/
	public function index ()
	{
		return $this->fetch();
	}
	/**
	* 会员列表
	* $param               搜索参数
	* director             主任权限
	* executive_director   主管权限
	* memberList           咨询师权限
	*/
	public function memberList ()
	{
		if (request()->isAjax()) {
			$uid = session('id');
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if (!empty($param['name'])) {
				$where['name'] = ['like', '%' . $param['name'] . '%'];
			}
			if (!empty($param['phone'])) {
				$where['phone'] = ['like', '%' . $param['phone'] . '%'];
			}
			if (!empty($param['grade'])) {
				$where['grade'] = $param['grade'];
			}
			if (!empty($param['status'])) {
                $where['status'] = $param['status'];
			}
			if(!empty($param['time'])){
				$start_time = strtotime(explode(" - ",$param['time'])[0]." 00:00:00");
				$end_time = strtotime(explode(" - ",$param['time'])[1]." 23:59:59");
				$where['entry_time|second_time']=array('between',array($start_time,$end_time));
			}
			//depart_id user_id
			if (!empty($param['depart_id'])) {
				$finance = new Finance();
				$departUserID = $finance->getAllRolesAndAllUsersByParentDepart($param['depart_id']);
				$where['create_uid'] = array('in',$departUserID['userArr']);
			}else {
				$canSee = session('can_see');
				$creaArr = [];
				foreach($canSee as $val){
					if(empty($val)){
						$creaArr = Db::name('user')->column('id');
					}else{
						array_push($creaArr,$val['create_uid']);
					}
				}
				$where['create_uid'] = array('in',$creaArr);
			}
			if(!empty($param['user_id'])){
				$where['create_uid'] = array('in',$param['user_id']);
			}
			$where['delete_status'] = array('neq',2);//是否是伪删除
//			$where['status'] = array('neq',8);//客户状态不能是释放状态
			$where['share'] = array('neq',1);//客户状态不能是分享状态
			$where['first_relation'] = array('neq',0);//客户不能是公共客户
			$member = new MemberModel();
			$selectResult = $member->getMemberByWhere($where, $offset, $limit);
			foreach($selectResult as $key=>&$vo){
				$vo['name'] = '<a href="'.url('member/memberInfo',['m_id'=>$vo['id']]).'">'.$vo['name'].'</a>';
				$vo['statusN'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
				$role_id = Db::name('user')->where(['id'=>$vo['relation_id']])->value('role_id');
				$department_id = Db::name('role')->where(['id'=>$role_id])->value('department_id');
				$vo['depar'] = Db::name('department')->where(['id'=>$department_id])->value('name');
				//强制释放
				if ($vo['status'] != 8){
					if($vo['relation_id'] == $uid){
						$vo['operate'] = showOperate($this->makeButton1($vo['id']));
					}else{
						if($vo['source'] == 0){
							$vo['operate'] = showOperate($this->makeButton2($vo['id']));
						}else{
							if($vo['status'] != 7){
								$vo['operate'] = showOperate($this->makeButton4($vo['id']));//强制释放
							}else{
								$vo['operate'] = showOperate($this->makeButton2($vo['id']));//查看跟踪
							}
						}
					}
				}else{
					$vo['operate'] = showOperate($this->makeButton2($vo['id']));
				}
				$vo['gradeN'] = Db::name('member_attr')->where(['id'=>$vo['grade']])->value('name');
			}
			$return['total'] = $member->getAllMember($where);// 总数据
			$return['rows'] = $selectResult;
			return json($return);
		}

		//客户等级
		$gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
		//客户状态
		$statusArr = Db::name('member_attr')->where(['pid'=>5])->select();
		foreach($statusArr as $key=>$val){
			if($val['id'] == 8){
				unset($statusArr[$key]);
			}
		}
		$this->assign([
			'gradeArr' => $gradeArr,
			'statusArr' => $statusArr
		]);
		return $this->fetch();
	}
	/**
	* 强制释放
	* status 改变
	*/
	public function releaseMem(){
		if(request()->isAjax()){
			$param = $_POST['param'];
			$member = new MemberModel();
			$returnMsg = $member->release($param);
			return $returnMsg;
		}
	}
	/**
	* 伪删除会员
	*/
	public function deleteList ()
	{
		$param = $_POST['param'];
		$member = new MemberModel();
		$returnMsg = $member->delMember($param);
		return $returnMsg;
	}
	//查看会员信息
	public function checkMember ()
	{
		$id = (int)input('param.id');

		$memTrackArr = Db::name('track_member')->where(['m_id'=>$id])->order('id desc')->select();
		foreach($memTrackArr as &$val){
			$val['time'] = date('Y-m-d H:i:s',$val['time']);
			$val['u_name'] = Db::name('user')->where(['id'=>$val['u_id']])->value('real_name');
			$val['m_name'] = Db::name('member')->where(['id'=>$val['m_id']])->value('name');
		}
		$this->assign([
			'memTrackArr' => $memTrackArr
		]);
		return $this->fetch();
	}

	/**
	* 修改客户信息
	*/
	public function memberEdit ()
	{
		$member = new MemberModel();
		if (request()->isPost()){
			$param = input('post.');
			$Status = Db::name('member')->where(['id'=>$param['id']])->value('status');
			if($Status == 9){
				$param['status'] = 6;
			}
			$flag = $member->memberEdit($param);
			return json(msg($flag['code'], $flag['data'], $flag['msg']));
		}
		//查看当前用户的订单信息
		$id = input('param.id');
		$or_where['m_id'] = $id;
		//2018-7-19 samsara 增 订单默认状态[status]
		$or_where['status'] = ['in',[1,4]];
		$orderArr = Db::name('order')->where($or_where)->order('id desc')->find();
		if(!empty($orderArr)){
				$orderArr['pay_typeN'] = Db::name('member_attr')->where(['id'=>$orderArr['pay_type']])->value('name');
				$orderArr['payment_methodN'] = Db::name('product_attr')->where(['id'=>$orderArr['payment_method']])->value('name');
				$orderArr['phone'] = Db::name('member')->where(['id'=>$id])->value('phone');
				$orderModel = new OrderModel();
				$orderInfo = $orderModel->getProductInfo($orderArr['id']);
				$orderArr['cofigArr'] = $orderInfo['cofigArr'][0];//产品配置
				$proList = $orderModel->getProductList($orderArr['school_id'],$orderArr['major_id']);//产品列表
				// print_r($orderArr);
				$this->assign([
						'orderArr' => $orderArr,
						'proList' => $proList
				]);
		}

		$returnMsg = $member->getOneMember($id);
		$returnMsg['statusN'] = Db::name('member_attr')->where(['id'=>$returnMsg['status']])->value('name');
		$returnMsg['gradeN'] = Db::name('member_attr')->where(['id'=>$returnMsg['grade']])->value('name');
		$returnMsg['source_originN'] = Db::name('member_attr')->where(['id'=>$returnMsg['source_origin']])->value('name');
		$returnMsg['time'] = date('Y-m-d',$returnMsg['time']);
		//客户等级
		$gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
		foreach ($gradeArr as $key => $value){
			if ($value['id'] == $returnMsg['grade']){
				unset($gradeArr[$key]);
			}
		}
		//客户状态
		$statusArr = Db::name('member_attr')->where(['pid'=>5])->select();
		foreach ($statusArr as $k => $val){
			if ($val['id'] == $returnMsg['status']){
				unset($statusArr[$k]);
			}
		}
		//支付方式
		$payTypeArr = Db::name('member_attr')->where(['pid'=>10])->select();
		//生源途径
		$source_origin = Db::name('member_attr')->where(['pid'=>32])->select();
		foreach ($source_origin as $k => $val){
			if ($val['id'] == $returnMsg['source_origin']){
				unset($source_origin[$k]);
			}
		}
		//客户附件
		$fileList = $returnMsg['id_photo'];
		$fileList = explode(',' , substr($fileList,1));
		$where['id'] = array('in',$fileList);
		$fileList = Db::name('attachment')->where($where)->select();
		$this->assign([
			'mid'        => $id,
			'memberArr'  => $returnMsg,
			'gradeArr'  => $gradeArr,
			'statusArr' => $statusArr,
			'payTypeArr' => $payTypeArr,
			'source_origin' => $source_origin,
			'fileList' => $fileList
		]);
		return $this->fetch();
	}
	/**
	* 根据时间段搜索相对应的追踪信息
	* @param $KL-time
	*/
	public function trackList(){
		if (request()->isAjax()){
			$param = input('post.');
			if (empty($param['time'])){
				return msg(-1, '','时间不能为空');
			}
			$where = [];
			$where['m_id'] = $param['mid'];
			//时间
			$start_time = strtotime(explode(" - ",$param['time'])[0].'00:00:00');
			$end_time = strtotime(explode(" - ",$param['time'])[1].'24:59:59');
			$where['time'] = array('between',[$start_time,$end_time]);
			$member = new MemberModel();
			$result = $member->getTrackList($where);
			return json($result);
		}
	}
	/**
	* 添加跟踪信息
	* @param $_post
	* @return array
	*/
	public function addTrack ()
	{
		$member = new MemberModel();
		$mid = (int)input('param.mid');
		$Mname = Db::name('member')->where(['id'=>$mid])->value('name');
		$uid = $_SESSION['think']['id'];
		$Uname = Db::name('user')->where(['id'=>$uid])->value('real_name');

		if (request()->isPost()){
			$param = input('post.');
			$param['u_id'] = $uid;
			if (empty($param['type'])) {
				return msg(-1, '','跟踪方式不能为空');
			}
			if (empty($param['years']) || empty($param['times'])) {
				return msg(-1, '','时间不能为空');
			}
			$param['time'] = strtotime($_POST['years'].$_POST['times']);
			$flag = $member->addTrack($param);
			return json(msg($flag['code'], $flag['data'], $flag['msg']));
		}
		//跟踪方式
		$trackArr = Db::name('member_attr')->where(['pid'=>25])->select();
		$this->assign([
			'mid'   => $mid,
			'Mname' => $Mname,
			'Uname' => $Uname,
			'trackArr' => $trackArr
		]);
		return $this->fetch();
	}
	/**
	* 查看跟踪信息
	* @param $id
	* @return array
	*/
	public function trackMember ()
	{
		$member = new MemberModel();
		if(request()->isAjax()){
			$id = $_POST['tid'];
			$track = $member->getTrackMember($id);
			$track['typeN'] = Db::name('member_attr')->where(['id'=>$track['type']])->value('name');
			$track['time'] = Date('Y-m-d H:i:s',$track['time']);
			return json($track);
		}
	}
	/**
	* 删除跟踪信息
	* @param $id
	* @return array
	*/
	public function trackDel ()
	{
		$id = $_POST['tid'];
		$member = new MemberModel();
		$returnMsg = $member->delTrack($id);
		return $returnMsg;
	}
	/**
	* 公共客户列表
	* 主管及主任以上可看
	* 属于资源库客户
	* @param $id
	* @return array
	*/
	public function wholeList ()
	{
		if (request()->isAjax()) {
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if (!empty($param['name'])) {
				$where['name'] = ['like', '%' . $param['name'] . '%'];
			}
			if (!empty($param['phone'])) {
				$where['phone'] = ['like', '%' . $param['phone'] . '%'];
			}
			$where['status'] = ['eq',9];//强制使用分配客源
			$where['source'] = ['eq',1];//来源是资料库客源
			$where['first_relation'] = ['eq',0];//由资源库录入的客户没有第一关联人
			$where['create_uid'] = session('id');//每个人录入的公共客户只能自己看和分配
			$member = new MemberModel();
			$selectResult = $member->getMemberByWhere($where, $offset, $limit);
			foreach($selectResult as $key=>&$vo){
				$vo['operate'] = showOperate($this->makeButton3($vo['id']));
				$vo['status'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
			}
			$return['total'] = $member->getAllMember($where);  // 总数据
			$return['rows'] = $selectResult;
			return json($return);
		}
		$userModel = new UserModel();
		$this->assign([
			'canseeUser' => $userModel->getLowerStaff()
		]);
		return $this->fetch();
	}
	/**
	* 添加资料库客源
	*/
	public function addResMember(){
		if(request()->isPost()){
			$param = input('post.');
			$param['grade'] = 0;
			$param['status'] = 9;
			$param['source'] = 1;//客户来源
			$param['entry_time'] = time();//时间判断(是否要释放)
			$param['create_uid'] = session('id');
			$MemberModel = new MemberModel();
			$flag = $MemberModel->addResMember($param);
			return json(msg($flag['code'], $flag['data'], $flag['msg']));
		}
		//生源途径
		$source_origin = Db::name('member_attr')->where(['pid'=>32])->select();
		$this->assign([
				'source_origin' => $source_origin
			]);
		return $this->fetch();
	}
	/**
	* 文件导入资源客户库数据
	*/
	public function resMemExcel(){
		$id = input('post.id');
		$path = DB::name('attachment')->where('id',$id)->value('path');
		vendor("PHPExcel.Classes.PHPExcel");
		$PHPExcel = new \PHPExcel();
		$objRead = new \PHPExcel_Reader_Excel2007();   //建立reader对象
		if(!$objRead->canRead($path)){
			$objRead = new \PHPExcel_Reader_Excel5();
			if(!$objRead->canRead($path)){
				die('No Excel!');
			}
		}
		$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

		$obj = $objRead->load($path);  //建立excel对象
		$currSheet = $obj->getSheet(0);   //获取指定的sheet表
		$columnH = $currSheet->getHighestColumn();   //取得最大的列号
		$columnCnt = array_search($columnH, $cellName);
		$rowCnt = $currSheet->getHighestRow();   //获取总行数

		$data = array();
		for($_row=1; $_row<=$rowCnt; $_row++){  //读取内容
			for($_column=0; $_column<=$columnCnt; $_column++){
				$cellId = $cellName[$_column].$_row;
				$cellValue = $currSheet->getCell($cellId)->getValue();
				if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串
					$cellValue = $cellValue->__toString();
				}
				$data[$_row][$cellName[$_column]] = $cellValue;
			}
		}
		$inData = [];
		foreach($data as $k => $v){
			if($k>1){
				if($v['A'] == ""){
					unset($data[$k]);
				}else{
					$inData[$k] = [
						'name' 		=> $v['A'],//姓名
						'phone' 	=> $v['B'],//电话
						'industry' 	=> $v['C'],//工作行业
						'adress' 	=> $v['D'],//联系地址
						'age' 		=> $v['E'],//年龄
						'weixin' 	=> $v['F'],//微信
						'qq' 		=> $v['G'],//QQ
						'grade'  	=> 0,//等级
						'status' 	=> 9,//状态
						'source' 	=> 1,//来源
						'entry_time'=> time(),//录入时间
						'create_uid'=> session('id'),//创建者
					];
				}
			}else{
				unset($data[$k]);
			}
		}

		DB::startTrans();
		try{
			DB::commit();
			foreach($inData as $v){
				DB::name('member')->insert($v);
			}
			return ['code'=>1,'msg'=>'导入成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'导入失败:'.$e->getMessage()];
		}
	}
	/**
	* 分配客户会员(主管OR主任)
	* 添加
	*/
	public function insertMember ()
	{
		$param = input('post.');
		$paramArr = $param['param'];
		$member = new MemberModel();
		$where = [];
		$where['status'] = 9;
		$where['first_relation'] = $param['uid'];
		$where['entry_time'] = time();
		$where['source'] = 1;//客户来源
		$where['create_uid'] = $param['uid'];//创建者id

		$returnMsg = $member->insMember($paramArr,$where);
		return $returnMsg;
	}
	/**
	* 客户属性
	* grade (等级) status(客户状态)
	* 确定 值 status 1.释放 2.成交 (不可更改)
	*/
	public function memberAttr (){
		if(request()->isAjax()){
			$depart = new DepartmentModel();
			$departs = $depart->getDepartmentList();
			$departs = getTree(objToArray($departs), false);
			return json(msg(1, $departs, 'ok'));
		}
		return $this->fetch();
	}
	/**
	* 分享列表(增)
	* 由分享的客户组成的列表
	* 可由主管分配
	*/
	public function shareList(){
		$uid = session('id');
		$role_id = Db::name('user')->where(['id'=>$uid])->value('role_id');
		$department_id =Db::name('role')->where(['id'=>$role_id])->value('department_id');
		$RoleModel = new RoleModel();
		$users = $RoleModel->getUsersByDepartId($department_id);//获取当前登录人所在部门的所有职员
		$userK = [];
		foreach($users as $key => $val){
			$userK[$key]['id'] = $val;
			$userN = Db::name('user')->where(['id'=>$val])->value('real_name');
			$userK[$key]['name'] = $userN;
		}
		if (request()->isAjax()) {
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if (!empty($param['name'])) {
				$where['name'] = ['like', '%' . $param['name'] . '%'];
			}
			if (!empty($param['phone'])) {
				$where['phone'] = ['like', '%' . $param['phone'] . '%'];
			}
			if (!empty($param['grade'])) {
				$where['grade'] = $param['grade'];
			}
			$where['share'] = 1;//分享状态
			$where['delete_status'] = array('neq',2);//是否是伪删除
			$where['create_uid'] = array('in',$users);//可查看的职员
			$member = new MemberModel();
			$selectResult = $member->getShareMember($where, $offset, $limit);
			foreach($selectResult as $key=>&$vo){
				$vo['status'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
				$vo['grade'] = Db::name('member_attr')->where(['id'=>$vo['grade']])->value('name');
				$vo['operate'] = showOperate($this->makeButton3($vo['id']));
			}
			$return['total'] = $member->getAllMember($where);  // 总数据
			$return['rows'] = $selectResult;

			return json($return);
		}
		//客户等级
		$gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
		$this->assign([
			'gradeArr' => $gradeArr,
			'userK' => $userK
		]);
		return $this->fetch();
	}
	/**
	* 分享/跟踪的职员分配
	*/
	public function ajaxShare(){
		if (request()->isAjax()) {
			$param = input('post.');
			if(empty($param['uid'])){
				return json(['code'=>2,'msg'=>'请选择分配职员']);
			}
			if(isset($param['status'])){
				$data['status'] = 6;
			}else{
				$data['share'] = 0;
			}
			$data['create_uid'] = $param['uid'];
			$data['second_relation'] = $param['uid'];
			$data['second_time'] = time();
			$memberModel = new MemberModel();
			$king = $memberModel->ajaxShare($param,$data);
			return json($king);
		}
	}
	/**
	* 释放列表(增)
	* 释放出来的列表
	* 由主管分配
	*/
	public function releaseList(){
		$uid = session('id');
		$role_id = Db::name('user')->where(['id'=>$uid])->value('role_id');
		$department_id =Db::name('role')->where(['id'=>$role_id])->value('department_id');
		$RoleModel = new RoleModel();
		$users = $RoleModel->getUsersByDepartIdCansee($department_id);//获取当前登录人所在部门的所有职员
		$userK = [];
		foreach($users as $key => $val){
			$userK[$key]['id'] = $val;
			$userN = Db::name('user')->where(['id'=>$val])->value('real_name');
			$userK[$key]['name'] = $userN;
		}
		if (request()->isAjax()) {
			$param = input('param.');
			$limit = $param['pageSize'];
			$offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if (!empty($param['name'])) {
				$where['name'] = ['like', '%' . $param['name'] . '%'];
			}
			if (!empty($param['phone'])) {
				$where['phone'] = ['like', '%' . $param['phone'] . '%'];
			}
			if (!empty($param['grade'])) {
				$where['grade'] = $param['grade'];
			}
			$where['share'] = 0;//分享状态
			$where['status'] = 8;//客户状态
			$canSee = session('can_see');
			$creaArr = [];
			foreach($canSee as $val){
				if(empty($val)){
					$creaArr = Db::name('user')->column('id');
				}else{
					array_push($creaArr,$val['create_uid']);
				}
			}
			$where['create_uid'] = array('in',$creaArr);
			$member = new MemberModel();
			$selectResult = $member->getMemberByWhere($where, $offset, $limit);
			foreach($selectResult as $key=>&$vo){
				$vo['status'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
				$vo['grade'] = Db::name('member_attr')->where(['id'=>$vo['grade']])->value('name');
				$vo['operate'] = showOperate($this->makeButton3($vo['id']));
			}
			$return['total'] = $member->getAllMember($where);  // 总数据
			$return['rows'] = $selectResult;

			return json($return);
		}
		//客户等级
		$gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
		$userModel = new UserModel();
		$this->assign([

		]);
		$this->assign([
			'gradeArr' => $gradeArr,
			'canseeUser' => $userModel->getLowerStaff(),
			'userK' => $userK
		]);
		return $this->fetch();
	}

	/**
	 * [2018-7-26]
	 * samsara
	 * 客户OR学生/基础信息/订单信息/流水信息
	 */
	 public function memberInfo(){
		 	$id = input('m_id');
			// 会员基本信息
			$memberModel = new MemberModel();
			$mem_baseInfo = $memberModel->getOneMember($id);
			$mem_baseInfo['status'] = Db::name('member_attr')->where(['id'=>$mem_baseInfo['status']])->value('name');
			$mem_baseInfo['grade'] = Db::name('member_attr')->where(['id'=>$mem_baseInfo['grade']])->value('name');
			$mem_baseInfo['source'] = $mem_baseInfo['source'] == 0 ? '业务录入' : '资料库客源';
			$mem_baseInfo['share'] = $mem_baseInfo['share'] == 0 ? '否' : '是';
			$mem_baseInfo['source_origin'] = Db::name('member_attr')->where(['id'=>$mem_baseInfo['source_origin']])->value('name');
			// 订单基本信息
			$ord_baseInfo = Db::name('order')->where(['m_id'=>$id])->order('id desc')->select();
			foreach($ord_baseInfo as &$val){
					$val['grade'] = Db::name('product_attr')->where(['id'=>$val['grade']])->value('name');
					$val['system'] = Db::name('product_attr')->where(['id'=>$val['system']])->value('name');
					$val['acquisition_mode'] = Db::name('product_attr')->where(['id'=>$val['acquisition_mode']])->value('name');
					$val['payment_method'] = Db::name('product_attr')->where(['id'=>$val['payment_method']])->value('name');
					$val['agent'] = Db::name('user')->where(['id'=>$val['agent']])->value('real_name');
					switch ($val['status']){
							case 0:
									$val['status'] = '已取消';
									break;
							case 1:
									$val['status'] = '进行中';
									break;
							case 2:
									$val['status'] = '已完成';
									break;
							case 3:
									$val['status'] = '退款';
									break;
							case 4:
									$val['status'] = '创建中';
									break;
						 default:
								 $val['status'] = '创建中';
					}
					// 所属流水
					$orderModel = new OrderModel();
					$orderA = $orderModel->getOrderInfo($val['id']);
					$val['accountArr'] = $orderA['account'];
					//计算学费差额[difference]
					$val['ready_pay'] = 0;
					foreach($val['accountArr'] as &$value){
							$value['receivables_time'] = ($value['receivables_time'] == 0) ? "-" : date('Y-m-d',$value['receivables_time']);
							// 流水来源[acc_source][cost][ready_pay]
							$value['ready_pay'] = 0;
							if($value['tuition']){
									$value['acc_source'] = '学费';
									$value['cost'] = $value['tuition'];
									// 计算已交学费[ready_pay]
									if($value['receivables_time'] != 0){
											$val['ready_pay'] += $value['tuition'];
									}
							}
							if($value['registration']){
									$value['acc_source'] = '报名费';
									$value['cost'] = $value['registration'];
							}
							if($value['material_cost']){
									$value['acc_source'] = '资料费';
									$value['cost'] = $value['material_cost'];
							}
							if($value['photo_collection']){
									$value['acc_source'] = '照片采集费';
									$value['cost'] = $value['photo_collection'];
							}
							//创建人
	            $value['create_uid']  = Db::name('user')->where('id',$value['create_uid'])->value('real_name');
					}
					//计算学费差额[difference]
					$val['difference'] = $val['tuition'] - $val['ready_pay'];
			}
			//学员基本信息
			$studentInfo = Db::name('student')->where(['m_id'=>$id])->select();
			foreach($studentInfo as &$val){
					$val['sex'] = ($val['sex'] == 1) ? '男' : '女';
					$val['grade'] = Db::name('member_attr')->where(['id'=>$val['grade']])->value('name');
					$val['roll_statusN'] = ($val['roll_status'] == 1) ? '有' : '无';
					switch ($val['school_roll']) {
						case '0':
							$val['school_roll'] = '报名中';
							break;
						case '1':
							$val['school_roll'] = '在读';
							break;
						case '2':
							$val['school_roll'] = '毕业';
							break;
						case '3':
							$val['school_roll'] = '休学';
							break;
						case '4':
							$val['school_roll'] = '退学';
							break;
						default:
							$val['school_roll'] = '在读';
							break;
					}
					// 时间转换
					if(empty($val['birthday']) || $val['birthday'] == 0){
							$val['birthday'] = '-';
					}else{
							$val['birthday'] = date('Y-m-d',$val['birthday']);
					}
					if(empty($val['test_time']) || $val['birthday'] == 0){
							$val['test_time'] = '-';
					}else{
							$val['test_time'] = date('Y-m-d',$val['test_time']);
					}
					if(empty($val['school_date']) || $val['birthday'] == 0){
							$val['school_date'] = '-';
					}else{
							$val['school_date'] = date('Y-m-d',$val['school_date']);
					}
					//获取学员成绩
					$education = new Education();
					$val['scoreList'] = $education->getScoreListByStid($val['id']);
			}
			// dump()
			$this->assign([
					'mem_baseInfo' => $mem_baseInfo,
					'ord_baseInfo' => $ord_baseInfo,
					'studentInfo' => $studentInfo,
			]);
		 	return $this->fetch();
	 }
	/**
	* 拼装操作按钮
	* @param $id 跟踪记录
	* @return array
	*/
	private function makeButton1($id)
	{
		return [
			'跟踪记录' => [
				'auth' => 'member/memberedit',
				'href' => url('member/memberedit', ['id' => $id]),
				'btnStyle' => 'success',
				'icon' => 'fa fa-paste',
			]
		];
	}
	/**
	* 查看信息 $id
	*/
	private function makeButton2($id)
	{
		return [
			'跟踪信息' => [
				'auth' => 'member/checkmember',
				'href' => url('member/checkmember', ['id' => $id]),
				'btnStyle' => 'danger',
				'icon' => 'fa fa-search',
			]
		];
	}
	/**
	* 添加按钮 $id
	* 公共客源库分配客源和二次释放Two release
	* distribution
	*/
	private function makeButton3($id)
	{
		return [
			'分配客源' => [
				'auth' => 'member/insertmember',
				'href' => 'javascript:distribution('.$id.')',
				'btnStyle' => 'danger',
				'icon' => 'fa fa-user-plus',
			],
			'释放客源' => [
				'auth' => 'member/tworelease',
				'href' => 'javascript:releasemem('.$id.')',
				'btnStyle' => 'danger',
				'icon' => 'fa fa-user-plus',
			]
		];
	}
	/**
	* 添加按钮 $id
	* 强制释放
	* distribution
	*/
	private function makeButton4($id)
	{
		return [
			'跟踪信息' => [
				'auth' => 'member/checkmember',
				'href' => url('member/checkmember', ['id' => $id]),
				'btnStyle' => 'danger',
				'icon' => 'fa fa-search',
			],
			'强制释放' => [
				'auth' => 'member/insertmember',
				'href' => 'javascript:releasemem('.$id.')',
				'btnStyle' => 'danger',
				'icon' => 'fa fa-user-times',
			]
		];
	}
}
